// pages/cooperation/cooperation.js
var tempUserList = []; //临时的用户列表
var page = 1; //用户列表的页数
var searchType = "全部"; //选择的分类
var isAdmination = 0; //是否在倒计时
var time = 0; //倒计时
var t = null; //定时器
var service_view = require("../../service/view.js");
var service_common = require("../../service/common.js");
var service_user = require("../../service/user.js");
var service_pay = require("../../service/pay.js");
var service_version = require("../../service/version.js");
var service_adv = require("../../service/adv.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userList: [],
    userInfo: [],
    nowTime: Date.parse(new Date()) / 1000,
    typeArray: getApp().globalData.typeArray,
    time_css: "display:none;",
    day: "",
    time: "",
    wrq_news: 0,
    user_news: 0,
    offon: false,
    fixedBol: false,
    wrq_page: 1,
    demandList: [],
    navIndex: 1, // tab切换
    downBolIsShow: false, // 是否展示下拉
    typeIndex: 0, // 类型选中
    modal: "",
    send_id: "",
    INDEX:-1,
    pg:1,
    wrq_offon:true,
    ishide:0
  },
  /**
   * 获取展示时间
   */
  showTime: function() {
    var that = this;
    service_user.getShowTime(function(res) {
      if (res.data.data > 0) {
        clearTimeout(t);
        time = 0;
        time = res.data.data;
        timeOut(that, time);
      } else {
        clearTimeout(t);
        time = 0;
        that.setData({
          day: "",
          time: "",
          time_css: "display:none;",
        })
      }
    })
  },
  /**
   * 页面加载
   */
  onLoad: function() {
    wx.hideShareMenu()
    var that = this;
    that.setData({
      typeArray: getApp().globalData.typeArray,
    })
    this.showTime()
    setInterval(function() {
      that.setData({
        scrollHide: "opacity:1;"
      })
    }, 1000)
    this.getWrqList();
    console.log(getApp().globalData.typeArray);
    this.getsyinfo()
  },
  // 获取页面配置信息
  getsyinfo:function(){
    service_common.fetchData(
      service_common.getUrl("user.sysconfig"), {
        openid: getApp().globalData.userInfo.openid
      },
      (res) => {
        console.log(res)
        if(res.data.code==0){
          this.setData({
            ishide: res.data.data.enable_topic
          })
        }
      },
      "GET"
    )
  },
  /**
   * 页面渲染
   */
  onShow: function() {
    var that = this;
    service_view.newReplyCount(this.newReplyCount);
    page = 1;
    this.getUserList();
    service_version.getIsAuditing(function(res) {
      if (res.data.status == 0) {
        that.setData({
          isCheck: false,
          no_data: "无数据"
        })
      } else {
        that.setData({
          isCheck: true
        })
      }
    })
    // this.User_new()
    // this.wrq_zan()
  },
  showBolIs: function() {
    this.setData({
      downBolIsShow: true,
      navIndex: 1
    });
  },
  //--列表切换
  navListTab: function(et) {
    let index = +et.currentTarget.dataset.index;
    // let showBol = index == 0 ? false : true;
    this.setData({
      navIndex: index,
      downBolIsShow: false
    });
    if (index == 0) {
      this.getWrqList();
    }
  },
  // 喜欢wrq
  setLike: function(e) {
    service_common.fetchData(service_common.getUrl("user.TopicLove"), {
      topic_id: e.currentTarget.dataset.id,
      openid: getApp().globalData.userInfo.openid
    }, (res) => {
      if (res.data.code == 0) {
        this.data.demandList[e.currentTarget.dataset.index]
        var pg = Math.ceil(e.currentTarget.dataset.index / 15)
        if (pg == 0) {
          pg = 1
        }
        this.getWrqList(pg, e.currentTarget.dataset.id, e.currentTarget.dataset.index)
      }
    }, "GET");
  },
  // 获取wrq列表
  getWrqList: function(pg = this.data.wrq_page, ty = -1, INDEX) {
    service_common.fetchData(service_common.getUrl("user.geDemandList"), {
      page: pg,
      openid: getApp().globalData.userInfo.openid
    }, (res) => {
      if (res.data.code == 0) {
        wx.hideToast()
        if (ty == -1) {
          if (this.data.wrq_page == 1) {
            this.setData({
              demandList: res.data.data
            })
          } else {
            if (res.data.data.length == 0) {
              if (this.data.demandList.length >= 10) {
                wx.showToast({
                  title: '数据加载完成',
                })
              }
              this.setData({
                wrq_page:this.data.wrq_page-1
              })
            } else {
              this.data.demandList = this.data.demandList.concat(res.data.data)
              this.setData({
                demandList: this.data.demandList,
                wrq_offon:true
              })
            }
          }
        } else {
          for (var i in res.data.data) {
            console.log(res.data.data[i].id + '------' + ty)
            console.log(res.data.data[i].id == ty)
            if (res.data.data[i].id == ty) {
              this.setData({
                [`demandList[${INDEX}]`]: res.data.data[i]
              })
              return
            }
          }
        }
      }

    }, "GET");
  },
  modalHide: function(e) {
    var target_id = e.target.id;
    if (target_id == '') {
      this.setData({
        modal: '',
        focus: false
      })
    }
  },
  formSubmit: function(e) {
    service_view.TopicReply(this.data.send_id, e.detail.value.content, res => {
      if(res.data.code==0){
        this.setData({
          modal: '',
          focus: false
        })
        this.getWrqList(this.data.pg, this.data.send_id, this.data.INDEX)
      }
    });
    this.setData({
      val: ""
    })
  },
  toDetail: function (e) {

    add_form_id(e.detail.formId)
    var openid = e.currentTarget.dataset.openid;
    wx.navigateTo({
      url: '/pages/new_demand_detail/new_demand_detail?openid=' + openid + '&id=' + e.currentTarget.id
    })
  },
  //点击展开评论模态框
  modalShow: function(e) {
    var pg = Math.ceil(e.currentTarget.dataset.index / 15)
    if (pg == 0) {
      pg = 1
    }
    this.setData({
      focus: true,
      modal: 'show',
      showOperation: '',
      send_id: e.currentTarget.dataset.id,
      INDEX: e.currentTarget.dataset.index,
      pg: pg
    })
  },
  // 类型选择
  navTypeSelect: function(et) {
    let index = +et.currentTarget.dataset.index;
    this.setData({
      typeIndex: index
    });
  },
  // 类型选择-确定
  navTypeSure: function(et) {
    this.setData({
      downBolIsShow: false,
      userList: []
    });
    tempUserList = [];
    page = 1;
    searchType = this.data.typeArray[this.data.typeIndex];
    this.getUserList();
  },
  //点击查看名片
  viewCard: function (e) {
    console.log(e)
    add_form_id(e.detail.formId);
    var openid = e.currentTarget.dataset.openid;

    wx.navigateTo({
      url: '/pages/other/other?openid=' + openid,
    })
  },
  toPublish: function () {
    wx.navigateTo({
      url: '/pages/publish/publish',
    })
  },
  toMyPublish: function () {
    wx.navigateTo({
      url: '/pages/demand_my/demand_my',
    })
  },
  // 类型选择-清空
  navTypeEmpty: function(et) {
    this.setData({
      typeIndex: 0,
      downBolIsShow: false,
      userList: []
    });
    tempUserList = [];
    page = 1;
    searchType = this.data.typeArray[0];
    this.getUserList();
  },
  //--关闭下拉列表
  closeDownList: function() {
    this.setData({
      downBolIsShow: false
    })
  },
  // 获取wrq点赞个数
  wrq_zan: function() {
    service_common.fetchData(service_common.getUrl("user.newLoveCount"), {
      openid: getApp().globalData.openid
    }, function(res) {
      // 
      this.setData({
        wrq_zan: res.data.data.new_love_count
      })
    }, "GET");
  },
  // 获取后台消息
  User_new: function() {
    service_adv.getAdvList((res) => {
      console.log('------++++++')
      var n = res.data.data.data.length
      service_adv.getSeeAdv(res => {
        this.setData({
          user_news: n - res.data.data.see_adv_list.length
        })
      })
    })
  },
  toAdv: function() {
    wx.navigateTo({
      url: '/pages/adv_list/adv_list',
    })
  },
  /**
   * 获取wrq新消息数
   */
  newReplyCount: function(res) {
    this.setData({
      wrq_news: res.data.data.new_reply_count
    })
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh: function() {
    var that = this;
    tempUserList = [];
    page = 1;
    this.setData({
      wrq_page:1,
      wrq_offon:true
    })
    if (this.data.navIndex==0){
      
      this.getWrqList()
    }else{
      this.getUserList();
      this.showTime();
    }
    
  },
  /**
   * 获取用户列表
   */
  getUserList: function() {
    var that = this;
    service_view.getFindList(page, searchType, function(res) {
      var data = res.data.data.data;
      if (data.length > 0) {
        for (var i = 0; i < data.length; i++) {
          var exsit = false;
          for (var j = 0; j < tempUserList.length; j++) {
            if (tempUserList[j].openid == data[i].openid) {
              exsit = true;
              break;
            }
          }
          if (!exsit) {
            tempUserList.push(data[i]);
          }
        }
        that.getUserListCB();
      } else {
        if (that.data.userList.length > 0) {
          wx.showToast({
            title: '已到底啦',
            image: '../../image/end.png',
            duration: 500
          });
        }
        wx.stopPullDownRefresh();
      }
      page++;
      wx.hideToast();
    })
  },
  /**
   * 获取用户列表回调函数
   */
  getUserListCB: function() {
    this.setData({
      userList: tempUserList
    });
    wx.hideLoading();
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    wx.showToast({
      title: '加载数据中',
      icon: 'loading',
      duration: 100000
    });
    if (this.data.navIndex == 0) {
      if (this.data.wrq_offon && this.data.demandList.length>10){
        this.data.wrq_offon=false
        this.data.wrq_page += 1
        this.setData({
          wrq_page: this.data.wrq_page,
          wrq_offon: this.data.wrq_offon
        })
        this.getWrqList()
      }else{
        wx.hideToast()
      }
    } else {
      this.getUserList();
    }
  },
  /**
   * 点击标签事件
   */
  itemSelect: function(e) {
    var typeArray = [];
    searchType = e.target.dataset.type;
    page = 1;
    for (var i = 0; i <= getApp().globalData.typeArray.length - 1; i++) {
      if (e.target.dataset.item == i) {
        typeArray[i] = [i, "#528aee", "19px", getApp().globalData.typeArray[i], "border-bottom:2px solid #528aee;"];
      } else {
        typeArray[i] = [i, "black", "18px", getApp().globalData.typeArray[i], ""];
      }
    }
    tempUserList = [];
    this.setData({
      userList: [],
      typeArray: typeArray
    });

    this.getUserList();
  },
  /**
   * 跳转到Find页面
   */
  toFind: function(e) {
    console.log(e);
    wx.navigateTo({
      url: "/pages/cooperation/other/other?openid=" + e.currentTarget.dataset.openid
    })
  },
  /**
   * 跳转到首页
   */
  to_share_submit: function(e) {
    add_form_id(e.detail.formId)
    var pages = getCurrentPages()
    wx.switchTab({
      url: "/pages/index/index",
    })
    getApp().globalData.currentStatu = "open"
  },
  /**
   * 开通百万曝光
   */
  pay: function(e) {
    wx.showModal({
      title: '提示',
      content: '需要前去下载APP',
      confirmText: "前往",
      success: function(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/aApp/aApp',
          })
        }
      }
    })
  },
  /**
   * 页面滑动时间
   */
  onPageScroll: function(scrollTop) {
    var that = this;
    that.setData({
      scrollHide: "opacity:0;"
    })
    let top = scrollTop.scrollTop;
    let query = wx.createSelectorQuery();
    query.select('#cardCooperation').boundingClientRect(function(res) {
      that.setData({
        fixedBol: top >= res.height - 10 ? true : false
      });
    }).exec();
  },
  /**
   * 我想出现在此
   */
  powerDrawer: function(e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  // 关闭分享
  close_: function() {
    this.setData({
      offon: true
    })
  },
  //转发设置
  onShareAppMessage: function() {

    // 设置转发的路径
    var share_path = 'pages/other/other?openid=' + getApp().globalData.userInfo.openid + "&r=" + Math.random(100000);
    return {
      title: "我是" + getApp().globalData.userInfo.nickname + getApp().globalData.share_title,
      desc: '一个名片社交的资源配对平台，找资源找合作你就来',
      path: share_path,
      success: function() {
        service_user.setUserShareTime(function(res) {
          if (res.data.code == 0) {
            wx.showToast({
              title: '递名片成功',
              icon: 'success',
              duration: 1000,
            });
            setTimeout(function() {
              wx.showToast({
                title: '获得一天展示权限！',
                icon: 'success',
                duration: 1000,
              });
            }, 1000)
          } else {
            wx.showToast({
              title: '递名片成功',
              icon: 'success',
              duration: 1500
            });
          }
        })
      },
      fail: res => {
        wx.showToast({
          title: '递名片失败',
          image: '../../image/cancel.png',
          duration: 2000
        });
      }
    }
  },
  /**
   * 动画
   */
  util: function(currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function() {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })

      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  }
})
/**
 * 添加form_id
 */
function add_form_id(form_id) {
  wx.request({
    url: getApp().globalData.API_Base_URL + '/formid/index/setFormId?openid=' + getApp().globalData.openid + '&formid=' +
      form_id,
  })
}
/**
 * 展示时间倒计时
 */
function timeOut(that, time) {
  t = setInterval(function() {
    time = time - 1;
    var day = Math.floor(time / 3600 / 24);
    var hr = Math.floor(time / 3600 % 24);
    if (hr < 10) {
      hr = "0" + hr;
    }
    var min = Math.floor(time / 60 % 60);
    if (min < 10) {
      min = "0" + min;
    }
    var sec = Math.floor(time % 60);
    if (sec < 10) {
      sec = "0" + sec;
    }
    that.setData({
      day: day + "天",
      time: hr + ":" + min + ":" + sec,
      time_css: "",
    })
  }, 1000);
  that.setData({
    time_css: "",
  })
}